package com.thomas.classloading;

import java.io.IOException;
import java.io.InputStream;

/**   
* @Description: TODO(用一句话描述该文件做什么) 
* @author thomas_liu  
* @date 2018年3月26日 下午11:36:18 
* @version V1.0   
*/
public class ClassLoaderTest {
	
//	protected synchronized Class<?> loadClass(String name, boolean resolve){
//		//首先，检查请求的类是否已经被加载过了
//		Class c = findLoadedClass(name);
//		
//		if(c == null){
//			try {
//				if(parent != null){
//					c = parent.loadClass(name , false);
//				}else{
//					c.findBootstrapClassOrNull(name);
//				}
//			} catch (ClassNotFoundException e) {
//				//如果父类加载器抛出ClassNotFoundException
//				//说明父类加载器无法完成加载请求
//			}
//			
//			if(c == null){
//				//在父类加载器无法加载的时候
//				//再调用本身的findClass方法来进行类加载
//				c = findClass(name);
//			}
//			
//		}
//		if(resolve){
//			resolveClass(c);
//		}
//		return c;
//	}
	
	/**
	 * @param name
	 * @return
	 */
	private Class findLoadedClass(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		
		ClassLoader myLoader = new ClassLoader() {

			@Override
			public Class<?> loadClass(String name) throws ClassNotFoundException {
				
				try {
					String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
					InputStream is = getClass().getResourceAsStream(fileName);
					if(is == null){
						return super.loadClass(name);
					}
					byte[] b = new byte[is.available()];
					is.read(b);
					return defineClass(name, b, 0, b.length);
					
				} catch (IOException e) {
					throw new ClassNotFoundException(name);
				}
			}
		};
		
		Object obj = myLoader.loadClass("com.thomas.classloading.ClassLoaderTest").newInstance();
		
		System.out.println(obj.getClass());
		System.out.println(obj instanceof com.thomas.classloading.ClassLoaderTest);
		
	}
	

}
